const util = require("./util")

const command = {
  crc16 : function(buffer) {
    const polynomial = 0xA001;  // 多项式，低位优先的0x8005反射版
    let crc = 0xFFFF;           // 初始值

    for (let byte of buffer) {
        crc ^= byte; // 将字节与 CRC 的低字节进行异或

        for (let i = 0; i < 8; i++) {
            if (crc & 0x0001) {
                crc = (crc >> 1) ^ polynomial;  // 如果最低位为1，右移后与多项式异或
            } else {
                crc = crc >> 1;  // 否则直接右移
            }
        }
    }

    crc = crc & 0xFFFF;  // 取低16位作为最终CRC值
    const lowByte = crc & 0xFF;          // 低8位
    const highByte = (crc >> 8) & 0xFF;  // 高8位


    // 返回补0后的4字符长度的字符串，转为16进制并大写
    return [lowByte, highByte]
  },

  getCommandCrc16: function(command) {
    // const data = Buffer.from(command);

    // 计算 CRC-16
    const crc = this.crc16(command);
    const result = command.concat(crc)

    return result
  },

  bmsSNCommand : function () {
    const data = this.getCommandCrc16([0x0F, 0x03, 0x10, 0x00, 0x00, 0x10])
    return data
  }, 

  bmsPackCommand : function () {
    const data = this.getCommandCrc16([0x0F, 0x03, 0x10, 0x10, 0x00, 0x10])
    return data
  },

  bmsOVPROTCommand : function () {
    const data = this.getCommandCrc16([0x0F, 0x03, 0x11, 0x0E, 0x00, 0x01])
    return data
  },

  parseSNResponse : function(res) {
    let hexString = res.substring(6, res.length-4)
    return util.hexToAscii2(hexString)
  }
}

module.exports = command